
package com.sm.shoplook.service.system.impl;

import com.sm.shoplook.config.ProjectProperties;
import com.sm.shoplook.dao.mapper.base.SmsRecordMapper;
import com.sm.shoplook.domain.base.SmsRecord;
import com.sm.shoplook.service.system.SmsService;
import com.sm.shoplook.util.SMSUtil;
import com.sm.shoplook.vo.base.ApiResult;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chenpy
 * @desc 短信
 * @date 2018/10/16 15:31
 * @see
 */
@Service
public class SmsServiceImpl implements SmsService {

	@Autowired
	private SMSUtil smsUtil;
	@Autowired
	private ProjectProperties projectProperties;
	@Autowired
    private SmsRecordMapper smsRecordMapper;

	@Override
	public ApiResult sendSms(String phoneNum) {
		String code = RandomStringUtils.randomNumeric(4);
		SmsRecord param = new SmsRecord();
		param.setPhoneNum(phoneNum);
        int count = smsRecordMapper.selectCount(param);
        if (count > 0) {
            smsRecordMapper.delete(param);
        }
        SmsRecord smsRecord = new SmsRecord();
        Date now = new Date();
        smsRecord.setCreateTime(now);
        smsRecord.setPhoneNum(phoneNum);
        smsRecord.setSmsCode(code);
        smsRecord.setExpireTime(DateUtils.addMinutes(now, 2));
        smsRecordMapper.insertSelective(smsRecord);
		Map<String, Object> map = new HashMap<>(1);
		map.put("code", code);
		return smsUtil.sendSms(phoneNum, projectProperties.getAliSms().getTemplateCode(), map);
	}
}
